﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Web.Mvc.ModelBinding;
using System.Reflection;

namespace MvcApplicationBindersSample.Binders {
    public class TryParseModelBinderProvider : ModelBinderProvider {

        public override IExtensibleModelBinder GetBinder(ControllerContext controllerContext, ExtensibleModelBindingContext bindingContext) {
            if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName)) {
                // the value provider can't give us anything for this model
                return null;
            }

            // is there a TryParse() method with the appropriate signature?
            MethodInfo tryParseMethod = bindingContext.ModelType.GetMethod("TryParse",
                new Type[] { typeof(string), bindingContext.ModelType.MakeByRefType() });

            if (tryParseMethod != null) {
                // return a binder that can handle this model
                return new TryParseModelBinder(tryParseMethod);
            }
            else {
                // this provider doesn't know how create a binder that can handle this model,
                // so just move on to the next provider
                return null;
            }
        }

    }
}
